package model

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"im/libs"
)

type Token struct {
	conn *redis.Client
}

type TokenInfo struct {
	Uid  uint64
	Addr string
}

func NewToken(redis *libs.Redis) (*Token, error) {
	conn := libs.NewRedisConn(redis)
	r := &Token{conn: conn}
	return r, nil
}

func (c *Token) Gen(uid uint64, addr string) (string, error) {
	m := fmt.Sprintf("%d:%s", uid, addr)
	h := md5.New()
	h.Write([]byte(m))
	token := hex.EncodeToString(h.Sum(nil))
	key := fmt.Sprintf("t_%s", token)
	s := TokenInfo{
		Uid:  uid,
		Addr: addr,
	}
	bin, e := json.Marshal(s)
	if e != nil {
		return "", e
	}
	e = c.conn.Set(key, bin, 0).Err()
	if e != nil {
		return "", e
	}
	return token, nil
}

func (c *Token) Get(token string) (*TokenInfo, error) {
	key := fmt.Sprintf("t_%s", token)
	s := &TokenInfo{}

	bin, e := c.conn.Get(key).Bytes()
	if e != nil {
		return nil, e
	}
	e = json.Unmarshal(bin, s)
	if e != nil {
		return nil, e
	}
	return s, nil
}
